import {
    getRequest
} from "./api";

export const initMenu = (router, store) => {
    //如果用户是刷新页面 直接返回不需请求
    if (store.state.routes.length > 0) {
        return;
    }
    //等于0则执行下面
    getRequest("/system/menu/").then(data => {
        if (data) {
            let fmtRoutes = formatRoutes(data);
            router.addRoutes(fmtRoutes);
            store.commit('initRoutes', fmtRoutes);
            //初始化
            store.dispatch('connect');
        }
    })
};

export const formatRoutes = (routes) => {
    let fmRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router;
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            meta: meta,
            children: children,
            component(resolve) {
                if (component.startsWith("Home")) {
                    require(['../views/' + component + '.vue'], resolve);
                } else if (component.startsWith("Info")) {
                    require(['../views/info/' + component + '.vue'], resolve);
                } else if (component.startsWith("Base")) {
                    require(['../views/base/' + component + '.vue'], resolve);
                } else if (component.startsWith("Pra")) {
                    require(['../views/pra/' + component + '.vue'], resolve);
                } else if (component.startsWith("Rec")) {
                    require(['../views/rec/' + component + '.vue'], resolve);
                } else if (component.startsWith("Eva")) {
                    require(['../views/eva/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sys")) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }

            }
        };
        fmRoutes.push(fmRouter);
    });

    return fmRoutes;
};